package com.jt.proxy;

import javax.swing.text.html.HTMLDocument;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxyFactory {
    public static Object getProxy(Object target){
        Class<?>[] interfaces = target.getClass().getInterfaces();
        ClassLoader classLoader = target.getClass().getClassLoader();
        Object proxy = Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result=null;
                try {
                    long l = System.currentTimeMillis();
                    System.out.println("事务开始");
                    result=method.invoke(target, args);
                    System.out.println("事务提交");
                    long l1 = System.currentTimeMillis();
                    System.out.println("用时:"+(l1-l)+"毫秒");
                } catch (Exception e){
                    e.printStackTrace();
                    System.out.println("事务回滚");
                }
             return result;
            }
        });
        return proxy;
    }
}
